//
//  CPLoadingView.m
//  CheckPOI
//
//  Created by lixiang on 12/1/14.
//  Copyright (c) 2014 Li Fei. All rights reserved.
//

#import "HKLoadingView.h"
#import "UIView+properties.h"
#import "HKCommonDefine.h"
#import "UIView+KSShow.h"
#import <Masonry/Masonry.h>

#define kFadeDuration 0.2
#define kIndicatorViewWidth 25
#define kbgViewWidth 50

@interface HKLoadingView ()

@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;

@end

@implementation HKLoadingView

+ (HKLoadingView *)loadingView
{
    static HKLoadingView *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[HKLoadingView alloc] init];
    });
    return instance;
}

- (id)init
{
    self = [super init];
    if (self) {
        _bgView = [[UIView alloc] init];
        _bgView.backgroundColor =  UIColorFromRGBA(0x000000, 0.4);
        _bgView.layer.cornerRadius = 6;
        _bgView.layer.masksToBounds = YES;
        [self addSubview:_bgView];
        [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.mas_equalTo(self);
            make.size.mas_equalTo(CGSizeMake(kbgViewWidth, kbgViewWidth));
        }];
        self.autoresizingMask = UIViewAutoresizingFlexibleTopMargin
                                | UIViewAutoresizingFlexibleBottomMargin
                                | UIViewAutoresizingFlexibleLeftMargin
                                | UIViewAutoresizingFlexibleRightMargin;
        
        self.indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        [_bgView addSubview:self.indicatorView];
        
        [self.indicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.mas_equalTo(self.bgView);
            make.size.mas_equalTo(CGSizeMake(kIndicatorViewWidth, kIndicatorViewWidth));
        }];
    }
    return self;
}

#pragma mark - public method
- (void)hideLoading
{
    WS
    [UIView animateWithDuration:kFadeDuration animations:^{
        self.alpha = 0.f;
    } completion:^(BOOL finished) {
        SS
        [self.indicatorView stopAnimating];
        [self removeFromSuperview];
    }];
}

- (void)showLoading
{
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    self.frame = CGRectMake(0, 0, screenSize.width, screenSize.height);
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self];
    self.alpha = 0.f;
    [_indicatorView startAnimating];
    [UIView animateWithDuration:kFadeDuration animations:^{
        self.alpha = 1.f;
    } completion:^(BOOL finished) {
    }];
}

@end
